package com.hcb.tonguetiphealth.widget.more;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.UpdateVersionManager;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.view.SearchActivity;
import com.hcb.tonguetiphealth.widget.GeneralWidget;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;

public class MoreWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "ResearchWidget";
	
	private Activity ctx;
	private Handler mHandler;
	private LinearLayout linearLayoutBack, llShare;
	private Button btSearch, btVersion,  btAboutus, btAdvice, btCheckVerion, btHistory, btEnvironment;
	
	private LinearLayout llPropose;
	private ListView dialogListView;
	
	public static final int IS_UPDATA = 0;
	public static final int UPDATA_CLIENT = 1;
	public static final int GET_UNDATAINFO_ERROR = 2;
	public static final int DOWN_ERROR = 3;
	public static final int KEEP_VERSION = 4;
	
	private UpdateVersionManager updateManager = null;
    private String currrentVersion = null;
    
    private static final String APP_ID = "wxebdcf431ff1175ee";
	//IWXAI 是第三方ap和微信通信的openapi接口
	private IWXAPI api;
//    private UpdateInfo info = null;
	
	
	public MoreWidget(Context context) {
		super(context);
		ctx = (Activity) context;
		inflate(context, R.layout.more, this);

		mHandler = new Handler(){
			
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取版本信息");
					break;
				case IS_UPDATA: 
					//对话框通知用户升级程序 
					dismissMessageDialog();
					System.out.println("---------- 显示");
					updateManager.showTree();
					updateManager.showUpdataDialog();
					break;
				case UPDATA_CLIENT:
					//下载应用程序--进度条显示 
					System.out.println("通知用户升级程序");
					updateManager.downLoadApk(Global.getServletdownapk());
					break;
				case GET_UNDATAINFO_ERROR:
					//服务器超时 
					System.out.println("获取服务器更新信息失败");
					dismissMessageDialog();
					showMessage(ctx, "获取版本信息失败,请稍后重试");
					break;	
				case DOWN_ERROR:
					//下载apk失败
					System.out.println("下载新版本失败");
					Toast.makeText(ctx, "更新失败,请稍后重试", Toast.LENGTH_LONG).show();
					break;	
				case KEEP_VERSION:
					//版本号相同，删除   .zip和.apk文件
					dismissMessageDialog();
					System.out.println("版本号相同无需升级 --> 删除   .zip和.apk文件");
					showMessage(ctx, "当前已是最新版本");
					updateManager.deleteZIP_APK();
					break;
				}
			}
		};
		bindView();
		bindEvent();

	}
	
	private void bindView(){
		linearLayoutBack = (LinearLayout)findViewById(R.id.more_linearlayout_back);
		llPropose = (LinearLayout)findViewById(R.id.more_linearlayout_propose);
	//	btVersion = (Button)findViewById(R.id.more_version_bt);
		btAboutus = (Button)findViewById(R.id.more_aboutus_bt);
		btSearch = (Button)findViewById(R.id.more_search_bt);
		btAdvice = (Button)findViewById(R.id.more_advice_bt);
		btCheckVerion = (Button)findViewById(R.id.more_vupdate_bt);
		btHistory = (Button)findViewById(R.id.more_history_bt);
		btEnvironment = (Button)findViewById(R.id.more_environment_bt);
		llShare = (LinearLayout)findViewById(R.id.more_linearlayout_share);
	}
	
	private void bindEvent(){
		linearLayoutBack.setOnClickListener(this);
		btSearch.setOnClickListener(this);
		llPropose.setOnClickListener(this);
	//	btVersion.setOnClickListener(this);
		btAboutus.setOnClickListener(this);
		btAdvice.setOnClickListener(this);
		btCheckVerion.setOnClickListener(this);
		btHistory.setOnClickListener(this);
		btEnvironment.setOnClickListener(this);
		llShare.setOnClickListener(this);
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.more_linearlayout_back:
			ctx.finish();
			break;
		case R.id.more_linearlayout_share:
			if (Global.user == null) {
				login();
			}else {
//				showSelectDialog();
				ctx.setContentView(new ContactsWidget(ctx));
			}
			break;
		case R.id.more_search_bt:
			ctx.startActivity(new Intent(ctx, SearchActivity.class));
			break;
		case R.id.more_linearlayout_propose:
			ctx.getIntent().putExtra("fromFlag", 0);
			ctx.setContentView(new StaticInfoWidget(ctx));
			break;
//		case R.id.more_version_bt:
//			ctx.getIntent().putExtra("fromFlag", 1);
//			ctx.setContentView(new StaticInfoWidget(ctx));
//			break;
		case R.id.more_aboutus_bt:
			ctx.getIntent().putExtra("fromFlag", 2);
			ctx.setContentView(new StaticInfoWidget(ctx));
			break;
		case R.id.more_advice_bt:
			ctx.setContentView(new AdviceWidget(ctx));
			break;
		case R.id.more_vupdate_bt:
			checkVersion();
			break;
		case R.id.more_history_bt:
			ctx.setContentView(new HistoryWidget(ctx));
			break;
		case R.id.more_environment_bt:
			ctx.getIntent().putExtra("fromFlag", 3);
			ctx.setContentView(new StaticInfoWidget(ctx));
			break;
		default:
			break;
		}
	}
 
	public void showSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
        final AlertDialog dialog = builder.create(); 
        /*builder.setPositiveButton("确定",null);    
        builder.setNegativeButton("取消",null); */  
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        
        LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.res_book_dialog_list, null); 
   
        dialog.setView(view);
        dialogListView = (ListView)view.findViewById(R.id.selection_listview);
        List<String>selectList = new ArrayList<String>();
    	selectList.add("分享给通讯录好友");
		selectList.add("分享给微信好友");
		SelectionListAdapter adapter = new SelectionListAdapter(ctx,
				selectList);
		dialogListView.setAdapter(adapter);
        dialogListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				switch (arg2) {
				case 0:
					ctx.setContentView(new ContactsWidget(ctx));
					dialog.cancel();
					break;
				case 1:
					//通过WXAPOfatory工厂，获取IWXAPI的实例
			        api = WXAPIFactory.createWXAPI(ctx, APP_ID, false);
			        // 将应用的appId注册到微信
			        boolean  sucess = api.registerApp(APP_ID);
			        System.out.println("注册："+sucess);
			        
			        String text = "hello";
			        // 初始化一个WXtextObject
			        WXTextObject textObject = new WXTextObject();
			        textObject.text = text;
			        
			        // 用WXTextObject对象初始化一个WxmediaMessage对象
			        WXMediaMessage msg = new WXMediaMessage();
			        msg.mediaObject = textObject;
			        msg.description = text;
			        
			        
			        // 构造一个req
			        SendMessageToWX.Req req = new SendMessageToWX.Req();
			        req.transaction = String.valueOf(System.currentTimeMillis());
			        req.message = msg;
			        //调用api接口发送数据到微信
			        api.sendReq(req);
			 
					dialog.cancel();
					break;
				default:
					break;
				}
			}
		});
        
        dialog.show(); 
    }
	
	
	private void checkVersion() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread() {

			@Override
			public void run() {
				updateManager = new UpdateVersionManager(ctx, mHandler);
				try {
					currrentVersion = updateManager.getVersionName();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (currrentVersion == null) {
					System.out.println("获取版本号失败！");
				} else {
					System.out.println("当前版本号：" + currrentVersion);
				}
				String checkVersion = updateManager.getUpdataInfo(Global
						.getServletcheckversion());
				// info =
				// updateManager.getUpdataInfo("http://192.168.1.108:80/update.xml");
				if (checkVersion == null) {
					System.out.println("获取版本号失败");
					mHandler.sendEmptyMessage(GET_UNDATAINFO_ERROR);
				} else {
					Message msg = mHandler.obtainMessage();
					if (checkVersion.equals(currrentVersion)) {
						msg.what = KEEP_VERSION;
					} else {
						msg.what = IS_UPDATA;
					}
					mHandler.sendMessage(msg);
				}
			}

		}.start();
	}
	
	@Override
	public void notifyAdapter() {
		
	}
}
